const { Service } = require('egg')

class IndexService extends Service {
  /**
   * 获取所有错误列表
   * @returns {Promise<{serverCount, errorCount, errorCount, appCount}>}
   */
  async list() {
    const { ctx } = this
    const {
      query,
      sort,
      filter,
    } = this.ctx.state.query
    // 非管理员只能查看自己的
    if (!ctx.user.isAdmin) {
      query.user = ctx.user._id
    }
    const { _limit = 20, _page = 1 } = ctx.state.page
    const items = await ctx.model.Error.find(query, filter || '-stream')
                           .sort(sort)
                           .populate(['action name', 'server name', 'user name'])
                           .skip((_page - 1) * _limit)
                           .limit(_limit)
    const meta = {
      _limit,
      _page,
      count: await ctx.model.Error.count(query),
    }
    return { items, meta }
  }

  /**
   * 创建错误
   * @returns {Promise<Promise<*>|Promise<void>|any>}
   */
  async create() {
    const { ctx } = this
    const user = ctx.user._id
    const { title, action, point, server, stream } = ctx.request.body
    // 验证
    return ctx.model.Error.create({
      title, action, point, server, stream, user,
    })
  }

  /**
   * 更新错误
   * @returns {Promise<Promise<Promise<*>|Promise<void>|any>|Promise<void>|any>}
   */
  async update() {
    const { ctx } = this
    const { id } = ctx.params
    await ctx.validateId()
    const data = await ctx.safeLoader('title,action,point,server,stream,user')
    const query = { _id: id }
    // 非管理员只能更新自己的
    if (!ctx.user.isAdmin) {
      query.user = ctx.user._id
    }
    return await ctx.model.Error.findOneAndUpdate(query, data)
  }
}

module.exports = IndexService